package com.topcent.tioxyc.xxljob;

import cn.hutool.json.JSONArray;
import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import com.topcent.tioxyc.constants.KeyConstant;
import com.topcent.tioxyc.pojo.BusinessProcess;
import com.topcent.tioxyc.pojo.Customer;
import com.topcent.tioxyc.pojo.InspectionData;
import com.topcent.tioxyc.pojo.Order0111;
import com.topcent.tioxyc.pojo.vo.ReceiptToDataVO;
import com.topcent.tioxyc.service.BusinessProcessService;
import com.topcent.tioxyc.util.ApiClient;
import com.topcent.tioxyc.util.ConnmeUtils;
import com.topcent.tioxyc.util.PurchaseCommunity;
import com.xxl.job.core.handler.annotation.XxlJob;
import lombok.extern.slf4j.Slf4j;
import org.apache.http.Header;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.bind.annotation.GetMapping;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @author: weidian
 * @date: 2025/1/6 10:53
 * @Description: 来货数量更新
 */
@Slf4j
@Component
public class StockQuantityXxlJob {

    @XxlJob("stockQuantityXxlJob")
    public void stockQuantityXxlJob() {
        List<Order0111> order0111s = new ArrayList<>();
        Header[] headers = ConnmeUtils.createHeaders();
        Map<String, Object> parameter = new HashMap<>();
        parameter.put("app_id", "6690c7633df0f4b90b4ef551");
        parameter.put("entry_id", "669df675b02f2a74e35ca2f9");
        boolean fale = true;
        String zh = "";
        do {
            if (!zh.isEmpty()) {
                parameter.put("data_id", zh);
            }
            parameter.put("limit", 100);
            String jsonSale = JSONUtil.toJsonStr(parameter);
            JSONObject jdySale = ApiClient.sendPostRequest(KeyConstant.Jian_URL + "/v5/app/entry/data/list", headers, jsonSale);
            String data = jdySale.getStr("data");
            JSONArray objects = JSONUtil.parseArray(data);
            List<Order0111> list = JSONUtil.toList(objects, Order0111.class);
            if (list.size() == 100) {
                zh = list.getLast().get_id();
            } else {
                fale = false;
            }
            order0111s.addAll(list);
        } while (fale);

        System.out.println("dererer+++"+order0111s.size());

        for (Order0111 order0111 : order0111s) {
            order0111.set_widget_1721978605698(0);
            order0111.set_widget_1721632911791(0);
            Map<String, Object> parameterCx = new HashMap<>();
            parameterCx.put("app_id", "64a7b7416bbd930007630ed5");
            parameterCx.put("entry_id", "64a7b81afc35ba00082dbcad");
            HashMap<String,String> hashMap=new HashMap<>();
            hashMap.put("purchasing_no", order0111.get_widget_1721628277543());
            hashMap.put("purchasing_hang", order0111.get_widget_1721628277558());
            List<InspectionData> inspectionDataList = PurchaseCommunity.
                    queryBased(parameterCx, headers,hashMap, InspectionData.class);
            if (inspectionDataList == null || inspectionDataList.isEmpty()) {
                // 跳过当前迭代
                continue;
            }
            for (InspectionData inspectionData : inspectionDataList) {
                if (inspectionData.getInspection_result().equals("NG")){
                    continue;
                }
                if (inspectionData.getInspection_place().equals("公司仓库")){
                    order0111.set_widget_1721978605698(inspectionData.getTotal_qty()+ order0111.get_widget_1721978605698());
                    order0111.set_widget_1721632911792(order0111.get_widget_1721978605698());
                } else {
                    order0111.set_widget_1721632911791(inspectionData.getTotal_qty() + order0111.get_widget_1721632911791());
                    order0111.set_widget_1721897497411(order0111.get_widget_1721632911791());
                }
            }
//            (工厂质检增加数量-广州仓)+(广州仓质检增加数量+工厂仓库存)+(广州仓+工厂仓库存)
            int i = (order0111.get_widget_1721632911791() + order0111.get_widget_1721978605698());
            order0111.set_widget_1721696459065(i);
            if (i>=order0111.get_widget_1721629214715()){
                order0111.set_widget_1721696459066("完成");
            }else {
                order0111.set_widget_1721696459066(null);
            }
            Updatck(headers, order0111);
        }

    }
    private void Updatck(Header[] headers, Order0111 order0111s) {
        Map<String, Object> parameterInster002 = new HashMap<>();
        parameterInster002.put("app_id", "6690c7633df0f4b90b4ef551");
        parameterInster002.put("entry_id", "669df675b02f2a74e35ca2f9");
        parameterInster002.put("is_start_trigger", "true");
        parameterInster002.put("data_id", order0111s.get_id());
        order0111s.set_id(null);
        parameterInster002.put("data", ConnmeUtils.convertEntityToMapNull(order0111s));
        String jsonSale = JSONUtil.toJsonStr(parameterInster002);
        log.info("修改采购改工厂数"+jsonSale);
        JSONObject entries = ApiClient.sendPostRequest(KeyConstant.Jian_URL + "/v5/app/entry/data/update", headers, jsonSale);
    }


    @Autowired
    private BusinessProcessService businessProcessService; // 注入 MyBatis-Plus 的 Service

    /**
     * 收款单To数据库
     * @return
     */
    @XxlJob("receiptToData")
    public String receiptToData() {
        String appId = "669cb709a73cc1289c49800e";
        String entryId = "669cb70dab60aa3f4a7bb8b2";
        Header[] headers = ConnmeUtils.createHeaders();
        // 获取到产品主数据数据。
        List<ReceiptToDataVO> voArrayList = new ArrayList<>();
        Map<String, Object> parameter = new HashMap<>();
        parameter.put("app_id", appId);
        parameter.put("entry_id", entryId);
        boolean fale = true;
        String zh = "";
        do {
            if (!zh.isEmpty()) {
                parameter.put("data_id", zh);
            }
            parameter.put("limit", 100);
            String jsonSale = JSONUtil.toJsonStr(parameter);
            JSONObject jdySale = ApiClient.sendPostRequest(KeyConstant.Jian_URL + "/v5/app/entry/data/list", headers, jsonSale);
            String data = jdySale.getStr("data");
            JSONArray objects = JSONUtil.parseArray(data);
            List<ReceiptToDataVO> list = JSONUtil.toList(objects, ReceiptToDataVO.class);
            if (list.size() == 100) {
                zh = list.getLast().get_id();
            } else {
                fale = false;
            }
            voArrayList.addAll(list);
        } while (fale);
        // . 转换为业务实体
        List<BusinessProcess> processes = new ArrayList<>();
        for (ReceiptToDataVO vo : voArrayList) {
            BusinessProcess process = new BusinessProcess();
            // 基础字段映射
            process.setFlowState(convertFlowState(vo.getFlowState()));
            process.setDocumentNumber(vo.get_widget_1721705341229());
            process.setDocumentDate(vo.get_widget_1724133481200());
            process.setPostingTime(vo.get_widget_1724133481201());
            process.setFinalReviewer(vo.get_widget_1732757161498());
            process.setAccountingOrgCurrency(vo.get_widget_1724211800327());
            process.setSelectedCustomer(vo.get_widget_1721612921295());
            process.setSelectedCurrency(vo.get_widget_1721611861794());
            process.setCustomerNumber(vo.get_widget_1721611861769());
            process.setCustomerName(vo.get_widget_1723531059390());
            process.setPayerName(vo.get_widget_1747895193823());
            process.setSettlementMethodDeposit(vo.get_widget_1735630551051());
            process.setSettlementMethodSupplementalDeposit(vo.get_widget_1735630551052());
            process.setSettlementMethodBalance(vo.get_widget_1735630551061());
            process.setCurrency(vo.get_widget_1721611861792());
            process.setExchangeRate(vo.get_widget_1721611861795());
            process.setTotalReceiptAmount(vo.get_widget_1721546510509());
            process.setReceiptContent(String.join(",", vo.get_widget_1721548605260())); // List转字符串
            process.setFreightCost(vo.get_widget_1721546510512());
            process.setFreightRelatedOrder(vo.get_widget_1721633850435());
            process.setMoldCost(vo.get_widget_1721546510511());
            process.setOtherCosts(vo.get_widget_1727063272241());
            process.setMoldRelatedOrderOrMaterialCode(vo.get_widget_1721633850436());
            process.setCustomerDepositUnrelatedOrder(vo.get_widget_1721548605272());
            process.setOrderAdvancePayment(vo.get_widget_1721546510510());
            process.setOrderBalancePayment(vo.get_widget_1721546510514());
            process.setOrderAdvancePaymentPercentage(vo.get_widget_1721546510516());
            process.setLastApprovalModificationDate(vo.getReview_date());
            process.setCreditInsuranceCustomer(vo.get_widget_1732245287011());
            process.setSummary(vo.get_widget_1721704225568());
            process.setActualHistoricalAdvancePayment(vo.get_widget_1721559059726());
            process.setActualHistoricalBalancePayment(vo.get_widget_1721977133294());
            process.setActualAccumulatedAdvancePayment(vo.get_widget_1721559059736());
            process.setActualAccumulatedBalancePayment(vo.get_widget_1721977133315());
            process.setTotalOrderAmountAdvance(vo.get_widget_1721552089625());
            process.setTotalOrderAmountBalance(vo.get_widget_1721552089606());
            process.setCostTypeOrderAdvance(vo.get_widget_1721706613848());
            process.setCostTypeFreightMold(vo.get_widget_1721802751108());
            process.setCostTypeOrderBalance(vo.get_widget_1721873235306());
            process.setCostTypeTransferFee(vo.get_widget_1721615447445());
            process.setTransferFee(vo.get_widget_1721548605262());
            process.setActualBankReceipt(vo.get_widget_1723789934971());
            process.setSelectedCashFlow(vo.get_widget_1721706367228());
            process.setReasonCode(vo.get_widget_1721706367230());
            process.setCostAttributedDepartment(vo.get_widget_1721615191384());
            process.setAttributedDepartment(vo.get_widget_1721698410441());
            process.setCompanyCode(vo.get_widget_1721614027869());
            process.setCostCenter(vo.get_widget_1721615191383());
            process.setCompanyName(vo.get_widget_1721614027868());
            process.setBankAccount(vo.get_widget_1721704635069());
            process.setBankName(vo.get_widget_1721611861771());
            process.setBankAccountNumber(vo.get_widget_1721611861774());
            process.setBankAccountName(vo.get_widget_1721611861775());
            process.setJournalEntryNumber(vo.get_widget_1721612921309());
            process.setSelectedCollectingBank(vo.get_widget_1723518416346());
            process.setCollectingBankAccount(vo.get_widget_1723518416344());
            process.setCollectingBankAccountNumber(vo.get_widget_1723519192633());
            process.setApprovalCompletionDate(vo.get_widget_1721704225530());
            process.setSingleLineText(vo.get_widget_1721980784673());
            process.setSubmissionTime(vo.getCreateTime());
            process.setUpdateTime(vo.getUpdateTime());

            // 特殊字段：解析JSON获取name
            process.setApplicationDepartment(parseName(vo.get_widget_1721611861780()));
            process.setApplicant(parseName(vo.get_widget_1721633850413()));
            process.setAttributedSalesman(parseName(vo.get_widget_1721614782726()));

            processes.add(process);
        }
        //  先清除数据库
        businessProcessService.remove(null);
        //  批量保存到数据库
        businessProcessService.saveBatch(processes);

        return "成功处理 " + processes.size() + " 条数据";
    }

    /**
     * 解析JSON字符串提取name字段
     */
    private String parseName(String jsonStr) {
        if (jsonStr == null || jsonStr.trim().isEmpty()) {
            return "";
        }
        try {
            JSONObject json = JSONUtil.parseObj(jsonStr);
            return json.getStr("name", "");
        } catch (Exception e) {
            return ""; // 解析失败返回空
        }
    }
    /**
     * 数字状态转文字描述（非空场景）
     * @param flowStateNum 接收的数字状态（2/1/0）
     * @return 对应的文字描述
     */
    private String convertFlowState(String flowStateNum) {
        return "2".equals(flowStateNum) ? "流程手动结束" :
                "1".equals(flowStateNum) ? "流程已完成" : "流程进行中";
    }
}
